package com.demo.producer.job.process;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.producer.entity.OTAEntity;
import com.demo.producer.producer.MyGateway;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * @author Hanson
 * @date 2022/9/28 18:06
 */
@Slf4j
@Service
public class TestProcess {

    @Resource
    private MyGateway myGateway;

    public void process(){
        String topic = "V2X/DOWN/D/0123123";

        OTAEntity otaData = new OTAEntity();
        otaData.setDId(otaData.getDId());
        otaData.setMsgFrame(otaData.getMsgFrame());
        otaData.setProtocolVersion(otaData.getProtocolVersion());
        otaData.setTimestamp(otaData.getTimestamp());
        otaData.setAck(otaData.getAck());
        otaData.setOTATime(otaData.getOTATime());
        otaData.setOTAUserId(otaData.getOTAUserId());
        otaData.setOTApassword(otaData.getOTApassword());
        otaData.setAuthMode(otaData.getAuthMode());
        otaData.setSoftwareVersion(otaData.getSoftwareVersion());
        otaData.setHardwareVersion(otaData.getHardwareVersion());
        otaData.setOTAtransprotocal(otaData.getOTAtransprotocal());

        File jsonFile = new File("D:/test/OTAModules.json");
        // 构建JSON对象
        try {
            String content = FileUtils.readFileToString(jsonFile, "UTF-8");
            JSONObject UpgradeFileJsonObject = JSONArray.parseObject(content);

            JSONArray otaModules = UpgradeFileJsonObject.getJSONArray("OTAModules");
            for (int i = 0;i < otaModules.size();i++){
                JSONObject otaModule = otaModules.getJSONObject(i);
                otaModule.remove("fileName");
            }
            otaData.setOTAModules(otaModules);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        this.myGateway.sendToMqtt(topic, 1, JSON.toJSONString(otaData));

        System.out.println("TOPIC:" + topic + "数据已下发" + JSON.toJSONString(otaData));
    }
}
